import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import nprogress from 'nprogress'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'
import asyncRoutes from '@/router/asyncRoutes'

const whiteList = ['/login', '/404']

const getFirseRoutesPermission = (permissions) => {
  const firseRoutesPermission = permissions.map(item => {
    return item.split(':')[0]
  })
  return Array.from(new Set(firseRoutesPermission))
}

const getSecondRoutesPermission = (permissions) => {
  const secondRoutesPermission = permissions.map(item => {
    return `${item.split(':')[0]}:${item.split(':')[1]}`
  })

  return Array.from(new Set(secondRoutesPermission))
}

const getButtonsPermission = (permissions) => {
  const buttonsPermission = Array.from(new Set(permissions.map(item => `${item.split(':')[0]}:${item.split(':')[1]}:${item.split(':')[2]}`)))
  store.commit('menus/updateButtons', buttonsPermission)
}

/* 配置全局前置路由守卫 */
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next(false)
      Message.warning('已经登录')
      nprogress.done()
    } else {
      if (store.getters.name) {
        next()
      } else {
        try {
          const { menus, permissions } = await store.dispatch('user/fetchUserInfo')
          // console.log('所有异步的路由', asyncRoutes)
          // console.log('用户所拥有的路由', permissions)
          const firseRoutesPermission = getFirseRoutesPermission(permissions)
          // console.log('筛选后的一级路由', firseRoutesPermission)
          const secondRoutesPermission = getSecondRoutesPermission(permissions)
          // console.log('筛选后的二级路由', secondRoutesPermission)
          getButtonsPermission(permissions)
          const resultRoutes = await store.dispatch('menus/getRoutes', { firseRoutesPermission, secondRoutesPermission })
          // console.log('筛选后的最终路由', resultRoutes)
          router.addRoutes([...resultRoutes, { path: '*', redirect: '/404', hidden: true }])
          next({ ...to, replace: true })
        } catch (error) {
          router.push({ path: '/login', query: { redirect: to.fullPath } })
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } })
      Message.warning('请您登录')
      nprogress.done()
    }
  }
})

/* 配置全局后置路由守卫 */
router.afterEach((to, from) => {
  nprogress.done()
  document.title = getPageTitle(to.meta.title)
})
